﻿#include <QCoreApplication>
#include <QJsonObject>
#include "JZCo.h"
#include "JZWebServer.h"
#include "JZAgent.h"

class JZColorAngetPage : public JZWebStaticPage
{
public:
    QJsonObject onCommand(const QJsonObject& obj)
    {        
        QString context = obj["message"].toString();
        QString result;
        jzco_await bool ret = m_agent.send(context, result);

        QJsonObject res;
        if (ret)
        {
            qDebug() << context << "->" << result;

            res["code"] = 0;
            res["message"] = result;
        }
        else
        {
            qDebug() << context << "-> recv error.";

            res["code"] = 1;
            res["message"] = "服务器错误";
        }               
        return res;
    }

    JZAgent m_agent;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);    

    jzco_init();
        
    JZWebServer web;

    QString chat_path = a.applicationDirPath() + "/WebRoot/chat.html";
    JZColorAngetPage *page = new JZColorAngetPage();
    page->setFile(chat_path);

    web.addPage("index.html", page);
    if(!web.start(8080))
    {
        qDebug() << "open file failed.";
        return 1;
    }   

    return a.exec();
}
